/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
function validateForm(formName, selector)
{   
    var selectedVal = document.forms[formName][selector].value;

    validationMsg = "";
    switch(selector){
        //Registration form
        case("name"):
            pattern = new RegExp("^[a-zA-Z ]{5,}$");
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter at least 5 characters (only alphabet and space allowed)";
            break;
        case("username"):
            pattern = new RegExp("^[a-zA-Z0-9._]{5,}$");
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter at least 5 alphanumeric characters (only alphanumeric and underscore allowed)";
            break;
        case("password"):
            pattern = new RegExp("^[\\s\\S]{6,}$");
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter at least 6 characters";

            /*repassword = document.forms[formName]["repassword"].value;
            if(repassword != selectedVal)
                document.getElementById("repassword_validation").innerHTML = "Password and Retype Password must match";
            else
                document.getElementById("repassword_validation").innerHTML = "";*/
            
            break;
        case("repassword"):
            password = document.forms[formName]["password"].value;
            
            if(password != selectedVal)
                validationMsg = "Password and Retype Password must match";
            break;
        case("birthdate"):
            pattern = new RegExp("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter a valid date format : (YYYY-MM-DD)";
            break;
        case("email"):
            pattern = new RegExp("^[a-zA-Z0-9._]+@{1}[a-zA-Z0-9]+.{1}[a-zA-Z0-9]{2,}$");
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter a valid email address";
            break;
        case("photo"):
            pattern = new RegExp("^[\\s\\S]*[(.bmp)|(.jpg)|(.jpeg)|(.png)]$");
            if(!pattern.test(selectedVal))
                validationMsg = "Please upload .bmp, .jpg, .jpeg, or .png files only";
            break;
        case("location"):
            pattern = new RegExp("^[\\s\\S]{5,}$");
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter at least 5 characters";
            break;

        //Upload form
        case("desc"):
            pattern = new RegExp("^[\\s\\S]{5,}$");
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter at least 5 characters";
            break;
        case("tag"):
            pattern = new RegExp("^[\\s\\S]{3,}$");
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter at least 3 characters";
            break;
        case("photodate"):
            pattern = new RegExp("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")
            if(!pattern.test(selectedVal))
                validationMsg = "Please enter a valid date format : (YYYY-MM-DD)";
            break;
    }
    
    document.getElementById(selector+"_validation").innerHTML = validationMsg;

    if(validationMsg == "")
        return true;
    else
        return false;
}

function validateSubmission(formName){
    retval = true;

    switch(formName){
        case("registration_form"):
            retval = validateForm(formName, "name");
            retval = validateForm(formName, "username");
            retval = validateForm(formName, "password");
            retval = validateForm(formName, "birthdate");
            retval = validateForm(formName, "email");
            retval = validateForm(formName, "photo");
            retval = validateForm(formName, "location");
            break;
        case("upload_form"):
            retval = validateForm(formName, "desc");
            retval = validateForm(formName, "tag");
            retval = validateForm(formName, "photodate");
            break;
    }
    
    return retval;
}

function toggleCalenderPopup(){
    var calendarPopupDOM = document.getElementById('calendarPopupTable');

    if(calendarPopupDOM.style.display == "block"){
        calendarPopupDOM.style.display = "none";
        return false;
    }
    else{
        calendarPopupDOM.style.display = "block";
        return true;
    }   
}

function makeTable(toggle, year, month, selector){
    now = new Date();
    table = document.getElementById('calendarPopupTable');
    
    //Remove all child element of <table id="calendarPopupTable">
    if(table.tHead)
        table.removeChild(table.tHead);

    if(table.tBodies[0])
        table.removeChild(table.tBodies[0]);

    //Toggle calendar pop up
    if(toggle){
        if(!toggleCalenderPopup())
            return;
    }

    row = new Array();
    col = new Array();

    //Create <thead> element
    thead = document.createElement('thead');

    //Prev, MonthYear, Next header
    tr1 = document.createElement('tr');
        th_prev_year = document.createElement('th');
            prev_year_href = document.createElement('a');
                prev_year_href.setAttribute('href', '#');
                prev_year_href.appendChild(document.createTextNode('<<'));
                prev_year_href.setAttribute('onclick', "calendarPopupPrevYear('" + selector + "')");
        th_prev_year.appendChild(prev_year_href);

        th_prev = document.createElement('th');
            prev_href = document.createElement('a');
                prev_href.setAttribute('href', '#');
                prev_href.appendChild(document.createTextNode('<'));
                prev_href.setAttribute('onclick', "calendarPopupPrevMonth('" + selector + "')");
        th_prev.appendChild(prev_href);

        th_MonthYear = document.createElement('th');
            th_MonthYear.setAttribute('colspan', '3');
        if(month == null)
            month = now.getMonth();
        if(year == null)
            year = now.getFullYear();
        th_MonthYear.appendChild(document.createTextNode(numberToMonth(month) + ' ' + year));

        th_next = document.createElement('th');
            next_href = document.createElement('a');
                next_href.setAttribute('href', '#');
                next_href.appendChild(document.createTextNode('>'));
                next_href.setAttribute('onclick', "calendarPopupNextMonth('" + selector + "')");
        th_next.appendChild(next_href);

        th_next_year = document.createElement('th');
            next_year_href = document.createElement('a');
                next_year_href.setAttribute('href', '#');
                next_year_href.appendChild(document.createTextNode('>>'));
                next_year_href.setAttribute('onclick', "calendarPopupNextYear('" + selector + "')");
        th_next_year.appendChild(next_year_href);

    tr1.appendChild(th_prev_year);
    tr1.appendChild(th_prev);
    tr1.appendChild(th_MonthYear);
    tr1.appendChild(th_next);
    tr1.appendChild(th_next_year);
    thead.appendChild(tr1);

    //Day header
    tr2 = document.createElement('tr');
        th1 = document.createElement('th');
        th1.appendChild(document.createTextNode('S'));
        tr2.appendChild(th1);

        th2 = document.createElement('th');
        th2.appendChild(document.createTextNode('M'));
        tr2.appendChild(th2);

        th3 = document.createElement('th');
        th3.appendChild(document.createTextNode('T'));
        tr2.appendChild(th3);

        th4 = document.createElement('th');
        th4.appendChild(document.createTextNode('W'));
        tr2.appendChild(th4);

        th5 = document.createElement('th');
        th5.appendChild(document.createTextNode('T'));
        tr2.appendChild(th5);

        th6 = document.createElement('th');
        th6.appendChild(document.createTextNode('F'));
        tr2.appendChild(th6);

        th7 = document.createElement('th');
        th7.appendChild(document.createTextNode('S'));
        tr2.appendChild(th7);
    thead.appendChild(tr2);

    table.appendChild(thead);

    //Append <tbody> to id 'calendarPopupTable'
    table.appendChild(makeTbody(year, month, selector));
}

function getPrevMonth(month){
    if(month - 1 >=0)
        return month-1;
    else
        return 11;
}

function getNextMonth(month){
    if(month+1 <= 11)
        return month+1;
    else
        return 0;
}

function makeTbody(year, month, selector){
    dateArray = new Array();

    firstDay = 0;
    //Filling up <tbody> element with <tr> and <td>
    for(i=1; i<=31; ++i){
        if(isValidDate(year, month, i)){
            dateArray[i-1] = new Date(year, month, i);
            if(i == 1)
                firstDay = new Date(year, month, i).getDay();
        }
    }

    //Create <tbody> element
    tbody = document.createElement('tbody');

    ctr = 0;
    for(i=0; i<6; ++i){
        row[i] = document.createElement('tr');
        for(j=0; j<7; ++j){
            col[j] = document.createElement('td');
            if(i*7 + j >= firstDay){
                tempDate = new Date(dateArray[ctr]);
                
                if(!isNaN(tempDate.getDate())){
                    content = document.createElement('a');
                    content.setAttribute('href', '#');
                    content.setAttribute('id', tempDate.getFullYear() + '-' + tempDate.getMonth() + '-' + tempDate.getDate());
                    content.setAttribute('onclick', "showDate('" + selector + "', this.id)");
                    content.appendChild(document.createTextNode(tempDate.getDate()));
                    col[j].appendChild(content);
                    ++ctr;
                }
            }
            row[i].appendChild(col[j]);
        }
        tbody.appendChild(row[i]);
    }

    return tbody;
}

function appendNumber(number){
    if(parseInt(number/10) == 0)
        return '0' + number;
    else
        return number;
}

function showDate(selector, date){
    selector_input = document.getElementById(selector);
    splitted = date.split(/[-]/);
    selector_input.value = splitted[0] + '-' + appendNumber((parseInt(splitted[1]))+1) + '-' + appendNumber(splitted[2]);

    toggleCalenderPopup();
}

function isValidDate(year, month, date){
    temp = new Date(year, month, date);
    return ((date==temp.getDate()) && (month==temp.getMonth()) && (year==temp.getFullYear()));
}

function monthToNumber(month){
    switch(month){
        case 'January':
            return 0;
            break;
        case 'February':
            return 1;
            break;
        case 'March':
            return 2;
            break;
        case 'April':
            return 3;
            break;
        case 'May':
            return 4;
            break;
        case 'June':
            return 5;
            break;
        case 'July':
            return 6;
            break;
        case 'August':
            return 7;
            break;
        case 'September':
            return 8;
            break;
        case 'October':
            return 9;
            break;
        case 'November':
            return 10;
            break;
        case 'December':
            return 11;
            break;
    }
}

function numberToMonth(number){
    switch(number){
        case 0:
            return 'January';
            break;
        case 1:
            return 'February';
            break;
        case 2:
            return 'March';
            break;
        case 3:
            return 'April';
            break;
        case 4:
            return 'May';
            break;
        case 5:
            return 'June';
            break;
        case 6:
            return 'July';
            break;
        case 7:
            return 'August';
            break;
        case 8:
            return 'September';
            break;
        case 9:
            return 'October';
            break;
        case 10:
            return 'November';
            break;
        case 11:
            return 'December';
            break;
    }
}

function getCurrentMonthYear(){
    table = document.getElementById('calendarPopupTable');
    return table.tHead.rows[0].cells[2].innerHTML;
}

function calendarPopupPrevYear(selector){
    monthYear = getCurrentMonthYear().split(/[ ]/);
    //alert(parseInt(monthYear[1])-1);
    makeTable(false, parseInt(monthYear[1])-1, parseInt(monthToNumber(monthYear[0])), selector);
}

function calendarPopupPrevMonth(selector){
    monthYear = getCurrentMonthYear().split(/[ ]/);
    makeTable(false, parseInt(monthYear[1]), getPrevMonth(parseInt(monthToNumber(monthYear[0]))), selector);
}

function calendarPopupNextYear(selector){
    monthYear = getCurrentMonthYear().split(/[ ]/);
    makeTable(false, parseInt(monthYear[1])+1, parseInt(monthToNumber(monthYear[0])), selector);
}

function calendarPopupNextMonth(selector){
    monthYear = getCurrentMonthYear().split(/[ ]/);
    makeTable(false, parseInt(monthYear[1]), getNextMonth(parseInt(monthToNumber(monthYear[0]))), selector);
}

function switchCss(){
    links = document.getElementsByTagName('link');
    head = document.getElementById('header_title');

    if(links[0].getAttribute('href') == '../public/media/stylesheet/style1.css') {
        links[0].setAttribute('href' , '../public/media/stylesheet/style2.css');
        head.innerHTML = document.title;
    } else {
        links[0].setAttribute('href' , '../public/media/stylesheet/style1.css');
        head.innerHTML = "";
    }
}